{% extends "base.html" %}

{% block title %}发布活动 - 校园生活助手{% endblock %}

{% block css %}
<style>
    .form-section {
        background-color: white;
        border-radius: 0.5rem;
        padding: 2rem;
        box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        margin-bottom: 1.5rem;
    }
    .section-title {
        font-size: 1.25rem;
        font-weight: 600;
        margin-bottom: 1.5rem;
        padding-bottom: 0.5rem;
        border-bottom: 2px solid #e9ecef;
    }
    .form-control:focus {
        border-color: #007bff;
        box-shadow: 0 0 0 0.2rem rgba(0,123,255,0.25);
    }
    .date-time-group {
        display: flex;
        gap: 1rem;
    }
    .date-time-group .form-group {
        flex: 1;
    }
    .image-upload-preview {
        margin-top: 1rem;
        max-width: 100%;
        max-height: 200px;
        display: none;
        border-radius: 0.5rem;
    }
    .tags-input {
        display: flex;
        flex-wrap: wrap;
        gap: 0.5rem;
        border: 1px solid #ced4da;
        border-radius: 0.25rem;
        padding: 0.5rem;
        min-height: 40px;
    }
    .tag {
        background-color: #007bff;
        color: white;
        border-radius: 1rem;
        padding: 0.25rem 0.75rem;
        display: flex;
        align-items: center;
        font-size: 0.875rem;
    }
    .tag-remove {
        margin-left: 0.5rem;
        cursor: pointer;
    }
    .tag-input {
        border: none;
        outline: none;
        flex: 1;
        min-width: 100px;
    }
    .color-palette {
        display: flex;
        gap: 0.5rem;
        flex-wrap: wrap;
        margin-top: 0.5rem;
    }
    .color-option {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        cursor: pointer;
        border: 2px solid transparent;
    }
    .color-option.selected {
        border: 2px solid #333;
    }
    .form-actions {
        display: flex;
        gap: 1rem;
        justify-content: flex-end;
        margin-top: 2rem;
    }
    .help-block {
        color: #6c757d;
        font-size: 0.875rem;
        margin-top: 0.25rem;
    }
    .char-count {
        text-align: right;
        font-size: 0.75rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }
</style>
{% endblock %}

{% block content %}
<div class="mb-6">
    <h1 class="text-2xl font-bold text-gray-800">
        <i class="fa fa-calendar-plus-o mr-2 text-primary"></i>发布活动
    </h1>
    <p class="text-gray-600">填写活动信息，与全校师生分享精彩活动</p>
</div>

<!-- 消息提示区域 -->
{% with messages = get_flashed_messages(with_categories=true) %}
    {% if messages %}
        {% for category, message in messages %}
            <div class="alert alert-{{ category }} fade-in mb-4" role="alert">
                <button type="button" class="close" data-bs-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                {{ message }}
            </div>
        {% endfor %}
    {% endif %}
{% endwith %}

<div class="form-section">
    <h2 class="section-title">活动基本信息</h2>
    <form method="POST" action="{{ url_for('add_activity') }}" enctype="multipart/form-data">
        {{ form.hidden_tag() }}
        
        <div class="mb-4">
            {{ form.title.label(class="form-label font-medium") }}
            {{ form.title(class="form-control", placeholder="请输入活动标题") }}
            {% if form.title.errors %}
                <div class="text-danger">
                    {% for error in form.title.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
            <div class="char-count" id="title-count">0/100</div>
        </div>
        
        <div class="mb-4">
            {{ form.category.label(class="form-label font-medium") }}
            {{ form.category(class="form-control") }}
            {% if form.category.errors %}
                <div class="text-danger">
                    {% for error in form.category.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
        </div>
        
        <div class="mb-4">
            <label class="form-label font-medium">活动标签</label>
            <div class="tags-input" id="tags-input">
                <!-- 标签将动态添加到这里 -->
                <input type="text" class="tag-input" placeholder="输入标签，按回车添加">
                <input type="hidden" name="tags" id="tags-hidden">
            </div>
            <div class="help-block">添加标签有助于其他同学更容易找到您的活动</div>
        </div>
        
        <div class="mb-4">
            {{ form.image.label(class="form-label font-medium") }}
            {{ form.image(class="form-control") }}
            {% if form.image.errors %}
                <div class="text-danger">
                    {% for error in form.image.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
            <img id="image-preview" class="image-upload-preview" src="" alt="活动图片预览">
            <div class="help-block">支持JPG、PNG、GIF格式，文件大小不超过5MB</div>
        </div>
        
        <div class="mb-4">
            {{ form.description.label(class="form-label font-medium") }}
            {{ form.description(class="form-control", rows=4, placeholder="简要描述活动内容") }}
            {% if form.description.errors %}
                <div class="text-danger">
                    {% for error in form.description.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
            <div class="char-count" id="description-count">0/500</div>
        </div>
    </div>
    
    <div class="form-section">
        <h2 class="section-title">活动时间与地点</h2>
        
        <div class="mb-4">
            <label class="form-label font-medium">活动时间</label>
            <div class="date-time-group">
                <div class="form-group">
                    {{ form.start_date(class="form-control", placeholder="开始日期") }}
                    {% if form.start_date.errors %}
                        <div class="text-danger">
                            {% for error in form.start_date.errors %}
                                <small>{{ error }}</small><br>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
                <div class="form-group">
                    {{ form.start_time(class="form-control", placeholder="开始时间") }}
                    {% if form.start_time.errors %}
                        <div class="text-danger">
                            {% for error in form.start_time.errors %}
                                <small>{{ error }}</small><br>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <div class="mb-4">
            <div class="form-check mb-2">
                <input type="checkbox" class="form-check-input" id="has-end-time" checked>
                <label class="form-check-label" for="has-end-time">设置结束时间</label>
            </div>
            <div class="date-time-group" id="end-time-group">
                <div class="form-group">
                    {{ form.end_date(class="form-control", placeholder="结束日期") }}
                    {% if form.end_date.errors %}
                        <div class="text-danger">
                            {% for error in form.end_date.errors %}
                                <small>{{ error }}</small><br>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
                <div class="form-group">
                    {{ form.end_time(class="form-control", placeholder="结束时间") }}
                    {% if form.end_time.errors %}
                        <div class="text-danger">
                            {% for error in form.end_time.errors %}
                                <small>{{ error }}</small><br>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
        
        <div class="mb-4">
            {{ form.location.label(class="form-label font-medium") }}
            {{ form.location(class="form-control", placeholder="请输入活动地点") }}
            {% if form.location.errors %}
                <div class="text-danger">
                    {% for error in form.location.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
        </div>
        
        <div class="mb-4">
            {{ form.max_participants.label(class="form-label font-medium") }}
            <div class="input-group">
                {{ form.max_participants(class="form-control", placeholder="输入最大参与人数") }}
                <div class="input-group-append">
                    <button type="button" class="btn btn-outline-secondary" id="set-unlimited">不限</button>
                </div>
            </div>
            {% if form.max_participants.errors %}
                <div class="text-danger">
                    {% for error in form.max_participants.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
        </div>
    </div>
    
    <div class="form-section">
        <h2 class="section-title">活动详情与设置</h2>
        
        <div class="mb-4">
            {{ form.details.label(class="form-label font-medium") }}
            {{ form.details(class="form-control", rows=8, placeholder="详细描述活动内容、流程、嘉宾介绍等") }}
            {% if form.details.errors %}
                <div class="text-danger">
                    {% for error in form.details.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
            <div class="help-block">您可以使用简单的HTML标签来格式化内容，如 &lt;br&gt; 换行，&lt;strong&gt; 加粗等</div>
        </div>
        
        <div class="mb-4">
            {{ form.important_notes.label(class="form-label font-medium") }}
            {{ form.important_notes(class="form-control", rows=3, placeholder="活动的重要注意事项") }}
            {% if form.important_notes.errors %}
                <div class="text-danger">
                    {% for error in form.important_notes.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
        </div>
        
        <div class="mb-4">
            {{ form.organizer_contact.label(class="form-label font-medium") }}
            {{ form.organizer_contact(class="form-control", placeholder="联系人邮箱或电话") }}
            {% if form.organizer_contact.errors %}
                <div class="text-danger">
                    {% for error in form.organizer_contact.errors %}
                        <small>{{ error }}</small><br>
                    {% endfor %}
                </div>
            {% endif %}
            <div class="help-block">其他同学可以通过这个联系方式与您取得联系</div>
        </div>
        
        <div class="mb-4">
            <label class="form-label font-medium">活动优先级设置</label>
            <div class="form-check mb-2">
                {{ form.is_important(class="form-check-input") }}
                {{ form.is_important.label(class="form-check-label") }}
            </div>
            <div class="form-check mb-2">
                {{ form.is_recommended(class="form-check-input") }}
                {{ form.is_recommended.label(class="form-check-label") }}
            </div>
            <div class="help-block">重要活动将在首页优先展示，推荐活动会获得更多曝光</div>
        </div>
        
        <div class="mb-4">
            <label class="form-label font-medium">活动主题色</label>
            <div class="color-palette">
                <div class="color-option selected" data-color="#007bff" style="background-color: #007bff;"></div>
                <div class="color-option" data-color="#28a745" style="background-color: #28a745;"></div>
                <div class="color-option" data-color="#dc3545" style="background-color: #dc3545;"></div>
                <div class="color-option" data-color="#ffc107" style="background-color: #ffc107;"></div>
                <div class="color-option" data-color="#17a2b8" style="background-color: #17a2b8;"></div>
                <div class="color-option" data-color="#6610f2" style="background-color: #6610f2;"></div>
                <div class="color-option" data-color="#fd7e14" style="background-color: #fd7e14;"></div>
                <div class="color-option" data-color="#20c997" style="background-color: #20c997;"></div>
            </div>
            <input type="hidden" name="theme_color" id="theme-color" value="#007bff">
            <div class="help-block">选择活动的主题色，将在活动卡片上显示</div>
        </div>
    </div>
    
    <div class="form-actions">
        <a href="{{ url_for('activities') }}" class="btn btn-secondary">
            <i class="fa fa-arrow-left mr-2"></i>取消
        </a>
        <button type="submit" class="btn btn-primary">
            <i class="fa fa-paper-plane-o mr-2"></i>发布活动
        </button>
    </div>
</form>
{% endblock %}

{% block js %}
<script>
    // 字符计数功能
    const titleInput = document.getElementById('title');
    const titleCount = document.getElementById('title-count');
    const descriptionInput = document.getElementById('description');
    const descriptionCount = document.getElementById('description-count');
    
    if (titleInput && titleCount) {
        titleInput.addEventListener('input', function() {
            const count = this.value.length;
            titleCount.textContent = `${count}/100`;
            
            if (count > 100) {
                titleCount.classList.add('text-danger');
            } else {
                titleCount.classList.remove('text-danger');
            }
        });
    }
    
    if (descriptionInput && descriptionCount) {
        descriptionInput.addEventListener('input', function() {
            const count = this.value.length;
            descriptionCount.textContent = `${count}/500`;
            
            if (count > 500) {
                descriptionCount.classList.add('text-danger');
            } else {
                descriptionCount.classList.remove('text-danger');
            }
        });
    }
    
    // 图片预览功能
    const imageInput = document.getElementById('image');
    const imagePreview = document.getElementById('image-preview');
    
    if (imageInput && imagePreview) {
        imageInput.addEventListener('change', function() {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                
                reader.onload = function(e) {
                    imagePreview.src = e.target.result;
                    imagePreview.style.display = 'block';
                }
                
                reader.readAsDataURL(this.files[0]);
            }
        });
    }
    
    // 标签输入功能
    const tagsInput = document.getElementById('tags-input');
    const tagInput = tagsInput.querySelector('.tag-input');
    const tagsHidden = document.getElementById('tags-hidden');
    const maxTags = 5;
    
    function updateTagsHidden() {
        const tags = Array.from(tagsInput.querySelectorAll('.tag span'))
            .map(tag => tag.textContent.trim())
            .join(',');
        tagsHidden.value = tags;
    }
    
    function addTag(tagText) {
        if (tagText && !tagsInput.querySelector(`.tag span:contains("${tagText}")`) && 
            tagsInput.querySelectorAll('.tag').length < maxTags) {
            const tag = document.createElement('div');
            tag.className = 'tag';
            tag.innerHTML = `
                <span>${tagText}</span>
                <span class="tag-remove">×</span>
            `;
            
            const removeBtn = tag.querySelector('.tag-remove');
            removeBtn.addEventListener('click', function() {
                tag.remove();
                updateTagsHidden();
                tagInput.focus();
            });
            
            tagsInput.insertBefore(tag, tagInput.lastElementChild);
            updateTagsHidden();
            tagInput.value = '';
        }
    }
    
    tagInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && this.value.trim()) {
            e.preventDefault();
            addTag(this.value.trim());
        }
    });
    
    // 结束时间显示/隐藏功能
    const hasEndTime = document.getElementById('has-end-time');
    const endTimeGroup = document.getElementById('end-time-group');
    
    if (hasEndTime && endTimeGroup) {
        hasEndTime.addEventListener('change', function() {
            if (this.checked) {
                endTimeGroup.style.display = 'flex';
            } else {
                endTimeGroup.style.display = 'none';
                // 清空结束时间的值
                document.getElementById('end_date').value = '';
                document.getElementById('end_time').value = '';
            }
        });
    }
    
    // 最大参与人数不限功能
    const setUnlimited = document.getElementById('set-unlimited');
    const maxParticipants = document.getElementById('max_participants');
    
    if (setUnlimited && maxParticipants) {
        setUnlimited.addEventListener('click', function() {
            if (maxParticipants.value === '') {
                maxParticipants.value = '0';
                this.textContent = '限制';
            } else {
                maxParticipants.value = '';
                this.textContent = '不限';
            }
        });
    }
    
    // 颜色选择功能
    const colorOptions = document.querySelectorAll('.color-option');
    const themeColor = document.getElementById('theme-color');
    
    colorOptions.forEach(option => {
        option.addEventListener('click', function() {
            // 移除所有选中状态
            colorOptions.forEach(opt => opt.classList.remove('selected'));
            // 添加当前选中状态
            this.classList.add('selected');
            // 更新隐藏输入值
            themeColor.value = this.getAttribute('data-color');
        });
    });
    
    // 表单提交时的验证
    const form = document.querySelector('form');
    
    form.addEventListener('submit', function(e) {
        let isValid = true;
        let errorMessage = '';
        
        // 验证标题
        if (!titleInput.value.trim()) {
            isValid = false;
            errorMessage += '请输入活动标题\n';
        }
        
        // 验证开始时间
        const startDate = document.getElementById('start_date').value;
        const startTime = document.getElementById('start_time').value;
        
        if (!startDate || !startTime) {
            isValid = false;
            errorMessage += '请设置活动开始时间\n';
        }
        
        // 验证结束时间（如果设置了）
        if (hasEndTime.checked) {
            const endDate = document.getElementById('end_date').value;
            const endTime = document.getElementById('end_time').value;
            
            if (!endDate || !endTime) {
                isValid = false;
                errorMessage += '请设置活动结束时间\n';
            } else if (startDate && startTime && endDate && endTime) {
                // 比较开始时间和结束时间
                const startDateTime = new Date(`${startDate}T${startTime}`);
                const endDateTime = new Date(`${endDate}T${endTime}`);
                
                if (endDateTime <= startDateTime) {
                    isValid = false;
                    errorMessage += '结束时间必须晚于开始时间\n';
                }
            }
        }
        
        // 验证地点
        const location = document.getElementById('location').value;
        if (!location.trim()) {
            isValid = false;
            errorMessage += '请输入活动地点\n';
        }
        
        // 如果有错误，阻止表单提交并显示错误信息
        if (!isValid) {
            e.preventDefault();
            alert(errorMessage);
        }
    });
    
    // 页面加载时的初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 触发初始字符计数
        if (titleInput && titleCount) {
            titleCount.textContent = `${titleInput.value.length}/100`;
        }
        
        if (descriptionInput && descriptionCount) {
            descriptionCount.textContent = `${descriptionInput.value.length}/500`;
        }
        
        // 如果最大参与人数为空，设置为不限
        if (setUnlimited && maxParticipants && maxParticipants.value === '0') {
            maxParticipants.value = '';
            setUnlimited.textContent = '不限';
        }
        
        // 自动填充当前日期和时间作为默认值
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        
        const currentDate = `${year}-${month}-${day}`;
        const currentTime = `${hours}:${minutes}`;
        
        if (!document.getElementById('start_date').value) {
            document.getElementById('start_date').value = currentDate;
        }
        
        if (!document.getElementById('start_time').value) {
            document.getElementById('start_time').value = currentTime;
        }
        
        // 自动填充结束时间为开始时间加2小时
        if (hasEndTime.checked && !document.getElementById('end_date').value && !document.getElementById('end_time').value) {
            document.getElementById('end_date').value = currentDate;
            
            let endHours = now.getHours() + 2;
            let endDay = now.getDate();
            let endMonth = now.getMonth();
            let endYear = now.getFullYear();
            
            if (endHours >= 24) {
                endHours -= 24;
                endDay += 1;
                
                // 处理月末情况
                const daysInMonth = new Date(endYear, endMonth + 1, 0).getDate();
                if (endDay > daysInMonth) {
                    endDay = 1;
                    endMonth += 1;
                    
                    // 处理年末情况
                    if (endMonth > 11) {
                        endMonth = 0;
                        endYear += 1;
                    }
                }
            }
            
            document.getElementById('end_time').value = `${String(endHours).padStart(2, '0')}:${minutes}`;
            
            // 如果日期发生了变化，更新结束日期
            if (endDay !== now.getDate() || endMonth !== now.getMonth() || endYear !== now.getFullYear()) {
                document.getElementById('end_date').value = `${endYear}-${String(endMonth + 1).padStart(2, '0')}-${String(endDay).padStart(2, '0')}`;
            }
        }
    });
</script>
{% endblock %}